<template>
  <div class="table-box">
    <ProTable
      ref="proTableRef"
      title="消息列表"
      :indent="20"
      :columns="columns"
      :search-columns="searchColumns"
      :request-api="getTableList"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button v-auth="'sys.message.add.btn'" type="primary" :icon="CirclePlus" @click="openMsgForm('新增公告')">
          新增公告
        </el-button>
        <el-button
          v-auth="'sys.message.del.btn'"
          type="danger"
          :icon="Delete"
          plain
          :disabled="!scope.isSelected"
          @click="batchDelete(scope.selectedListIds)"
        >
          批量删除角色
        </el-button>
      </template>
      <template #isPublished="scope">
        <el-switch
          v-model="scope.row.isPublished"
          :active-value="'T'"
          :inactive-value="'F'"
          :loading="switchLoading"
          :before-change="() => changeDataScope(scope.row)"
        />
      </template>
      <template #operation="{ row }">
        <el-button
          v-auth="'sys.message.update.btn'"
          type="primary"
          link
          :icon="EditPen"
          @click="openMsgForm('编辑消息', row, false)"
        >
          编辑
        </el-button>
        <el-button v-auth="'sys.message.del.btn'" type="primary" link :icon="Delete" @click="deleteInfo(row)"> 删除 </el-button>
      </template>
    </ProTable>
    <MsgForm ref="msgFormRef" />
  </div>
</template>

<script setup lang="ts">
import { CirclePlus, Delete, EditPen, Lock } from '@element-plus/icons-vue';
import ProTable from '@/components/ProTable/index.vue';
import { useHandleData } from '@/hooks/useHandleData';
import { publish, addMsg, deleteMsg, editMsg, getMsgList, getDetileMsg } from '@/api/modules/system/sysMessage';
import MsgForm from '@/views/system/messageManage/components/MsgForm.vue';
import type { ColumnProps, ProTableInstance, SearchProps } from '@/components/ProTable/interface';
import { ref } from 'vue';
import { useOptionsStore } from '@/stores/modules/options';
import { ElMessage, ElMessageBox } from 'element-plus';
defineOptions({
  name: 'MsgManage'
});
const optionsStore = useOptionsStore();
// 表格配置项
const columns = [
  { type: 'selection', width: 80, selectable: row => row.isLock !== 'T' },
  { prop: 'title', label: '标题' },
  {
    prop: 'type',
    label: '公告类型',
    tag: true,
    enum: optionsStore.getDictOptions('sys_message'),
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'content', label: '内容' },
  { prop: 'isPublished', label: '是否发布' },
  {
    prop: 'sendType',
    label: '发送对象',
    tag: true,
    enum: optionsStore.getDictOptions('sys_message_send_type'),
    fieldNames: { label: 'codeName', value: 'id', tagType: 'callbackShowStyle' }
  },
  { prop: 'createdAt', label: '创建时间' },
  { prop: 'updateAt', label: '修改时间' },
  { prop: 'sendAt', label: '上一次发布时间' },
  { prop: 'operation', label: '操作', width: 200, fixed: 'right' }
];
// 表格配置项
const searchColumns: SearchProps[] = [
  { prop: 'title', label: '标题名称', el: 'input' },
  {
    prop: 'type',
    label: '公告类型',
    el: 'select',
    enum: optionsStore.getDictOptions('sys_message'),
    fieldNames: { label: 'codeName', value: 'id' }
  },
  {
    prop: 'isPublished',
    label: '是否发布',
    el: 'select',
    enum: [
      { label: '已发布', value: 'T' },
      { label: '未发布', value: 'F' }
    ]
  }
];

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTableRef = ref<ProTableInstance>();
const switchLoading = ref(false);
// 获取table列表
const getTableList = (params: any) => getMsgList(params);

const msgFormRef = ref();
const openMsgForm = (title, row = {}, isAdd = true) => {
  const params = {
    title,
    row: { ...row },
    api: isAdd ? addMsg : editMsg,
    getTableList: proTableRef.value?.getTableList
  };
  msgFormRef.value?.acceptParams(params);
};

// 删除信息
const deleteInfo = async (params: any) => {
  await useHandleData(deleteMsg, { ids: [params.id] }, `删除【${params.title}】消息`);
  proTableRef.value?.getTableList();
};

// 批量删除信息
const batchDelete = async (ids: (string | number)[]) => {
  await useHandleData(deleteMsg, { ids }, '删除所选消息');
  proTableRef.value?.clearSelection();
  proTableRef.value?.getTableList();
};

const changeDataScope = params => {
  switchLoading.value = true;
  const handleSuccess = (resolve: (value: boolean | PromiseLike<boolean>) => void) => {
    setTimeout(() => {
      switchLoading.value = false;
      ElMessage.success('发布公告成功');
      resolve(true);
    }, 200);
  };

  const handleError = (reject: (reason?: any) => void) => {
    setTimeout(() => {
      switchLoading.value = false;
      reject();
    }, 200);
  };

  return new Promise((resolve, reject) => {
    if (params.isPublished == 'F') {
      ElMessageBox.confirm(`您确认要发布 [${params.title}] 公告吗? `, '温馨提示', { type: 'warning' })
        .then(() => {
          publish({ id: params.id, isPublished: 'T' })
            .then(() => handleSuccess(resolve))
            .catch(() => handleError(reject));
        })
        .catch(() => {
          switchLoading.value = false;
        });
    } else {
      publish({ id: params.id, isPublished: 'F' })
        .then(() => handleSuccess(resolve))
        .catch(() => handleError(reject));
    }
  });
};
</script>
